package com.taobao.fanli.controller;

import com.taobao.api.internal.mapping.RequestXmlBodyType;
import com.taobao.fanli.common.RestResponse;
import com.taobao.fanli.dao.model.User;
import com.taobao.fanli.postbean.RegisterBean;
import com.taobao.fanli.postbean.UpdatePasswordBean;
import com.taobao.fanli.service.LoginService;
import com.taobao.fanli.utils.CookieUtil;
import com.taobao.fanli.vo.Login;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Tao on 2018/4/19.
 */
@Api(value="登录接口api", description = "登录接口api")
@RestController
@RequestMapping(value = "/sso")
public class LoginController {

    private static final Logger logger = LoggerFactory.getLogger("LoginController");

    @Resource
    private LoginService loginService;

    /**
     * 登录
     * @param account
     * @param password
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ApiOperation(value="登录", notes="登录接口", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "account", value = "帐号", required = true, dataType = "String",
                    paramType = "query"),
            @ApiImplicitParam(name = "password", value = "密码", required = true, dataType = "String",
                    paramType = "query")
    })
    public RestResponse login(
            @RequestParam(value = "account") String account,
            @RequestParam(value = "password") String password,
            HttpServletRequest request, HttpServletResponse response
    ){
        try {
            Login login = loginService.login(account, password);
            loginService.setUserByCookie(login, response);
            return new RestResponse(login);
        } catch (Exception e) {
            return new RestResponse(e.getMessage(), 505);
        }
    }

    /**
     * 更新密码
     * @param updatePasswordBean
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/updatePassword", method = RequestMethod.POST)
    @ApiOperation(value="更新密码", notes="更新密码接口", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "oldPassword", value = "老密码", required = true, dataType = "String",
                    paramType = "query"),
            @ApiImplicitParam(name = "password", value = "新密码", required = true, dataType = "String",
                    paramType = "query"),
            @ApiImplicitParam(name = "confirmPassword", value = "确认密码", required = true, dataType = "String",
                    paramType = "query")
    })
    public RestResponse updatePassword(@Valid UpdatePasswordBean updatePasswordBean,
                                       BindingResult result,
                                       HttpServletRequest request,
                                       HttpServletResponse response
    ){
        if(result.hasErrors()){
            List<ObjectError> allErrors = result.getAllErrors();
            for (ObjectError allError : allErrors){
                return new RestResponse(allError.getDefaultMessage(), 505);
            }
        }
        Login userByCookie = loginService.getUserByCookie(request);
        if(userByCookie == null){
            return new RestResponse("用户没有登录", 305);
        }
        if(!updatePasswordBean.getPassword().equals(updatePasswordBean.getConfirmPassword())){
            return new RestResponse("新密码不正确", 505);
        }
        try {
            loginService.checkOldPassword(userByCookie, updatePasswordBean.getOldPassword());
        } catch (RuntimeException e) {
            return new RestResponse("老密码不正确", 505);
        }
        loginService.updatePassword(userByCookie, updatePasswordBean.getPassword());
        return new RestResponse("success");
    }

    /**
     * 检查用户是否登录
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/check", method = RequestMethod.GET)
    @ApiOperation(value="检查用户是否登录", notes="检查用户是否登录", httpMethod = "GET")
    public RestResponse checkUserLogin(
            HttpServletRequest request,
            HttpServletResponse response
    ){
        Login userByCookie = loginService.getUserByCookie(request);
        if(userByCookie == null){
            return new RestResponse("用户没有登录", 305);
        }
        return new RestResponse(userByCookie);
    }

    /**
     * 登出接口
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/loginOut", method = RequestMethod.GET)
    @ApiOperation(value="登出接口", notes="登出接口", httpMethod = "GET")
    public RestResponse loginOut(
            HttpServletRequest request,
            HttpServletResponse response
    ){
        Login login = loginService.getUserByCookie(request);
        if(login == null){
            return new RestResponse("用户没有登录", 305);
        }
        loginService.deleteUserByCookie(response);
        return new RestResponse("success");
    }

    /**
     * 注册代码
     * @param registerBean
     * @param result
     * @return
     */
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    @ApiOperation(value="注册接口", notes="注册接口", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "account", value = "帐号", required = true, dataType =
                    "String", paramType = "query"),
            @ApiImplicitParam(name = "password", value = "密码", required = true, dataType =
                    "String", paramType = "query"),
            @ApiImplicitParam(name = "nickName", value = "昵称", required = true, dataType =
                    "String", paramType = "query"),
            @ApiImplicitParam(name = "realName", value = "姓名", required = true, dataType =
                    "String", paramType = "query"),
            @ApiImplicitParam(name = "alipay", value = "支付宝帐号", required = true, dataType =
                    "String", paramType = "query")
    })
    public RestResponse registerController(
            @Valid RegisterBean registerBean, BindingResult result
    ){
        if(result.hasErrors()){
            List<ObjectError> allErrors = result.getAllErrors();
            for (ObjectError allError : allErrors){
                return new RestResponse(allError.getDefaultMessage(), 505);
            }
        }
        try {
            Integer userId = loginService.register(registerBean);
            Map<String, Integer> map = new HashMap<>();
            map.put("id", userId);
            return new RestResponse(map);
        } catch (RuntimeException e) {
            return new RestResponse(e.getMessage(), 505);
        }
    }
}
